<?php
namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
class Login extends Controller
{
    public function signin($msg='0',$lname="")
    {
    	//错误列表
        $error_text=['','验证码错误','帐号或密码错误','您的帐号已被冻结,请联系管理员'];
        $error_message='';
       	switch ($msg) {
       		case '0':$msg=0;break;
       		case '1':$msg=1;break;
       		case '2':$msg=2;break;
       		case '3':$msg=3;break;
       		default:$msg=0;break;
       	}
        $error_message=$error_text[$msg];
        
        $this->assign("lname",$lname);
        $this->assign("msg",$msg);
        $this->assign("error_message",$error_message);
        return $this->fetch('signin');
    }

    /**
     * Curl版本
     * 使用方法：
     * $post_string = "app=request&version=beta";
     * request_by_curl('http://www.jb51.net/restServer.php', $post_string);
     */
    function request_by_curl($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'X-AjaxPro-Method:ShowList',
            'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36'
        ));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    //登录验证
    public function checkLog(){
    	$request = Request::instance();

    	//判断是否post提交数据
    	if($request->has("login_name","post")&&$request->has("login_pwd","post")&&$request->has("login_verify","post")){
    		$data=$request->post();//接收数据

    		//验证玛是否正确
    		$verify=md5(strtolower($data["login_verify"]));
    		$true_verify=Session::get("verify");
    		if($verify==$true_verify){
    			$user = Db::table('users')->where('login_name',trim($data["login_name"]))->find();
    			if($user){
    				if($user["login_pwd"]==md5(md5(trim($data["login_pwd"])))){
    					if($user["state"]==1){
                            Session::clear();
//使用方法
                            $punanme=$user["login_name"];
                           // if($punanme=="B")
                             //   $punanme="A";
                            $post_data = array(
                                'loginName' => $punanme,
                                'password' => $user["login_pwd"],
                                'tenantCode' => ''
                            );
                            $ch = curl_init();
                            //curl_setopt($ch, CURLOPT_URL,            "http://61.129.51.183:10010/hzwf73/horizon/workflow/rest/user/login.wf" );
                            curl_setopt($ch, CURLOPT_URL,            "http://61.129.51.183:10010/workflow/horizon/workflow/rest/user/login.wf" );
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
                            curl_setopt($ch, CURLOPT_POST,           1 );
                            curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
                            curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
                            $return = curl_exec($ch);

                            $return = json_decode($return);

                            if($return->success==true){
                                //print_r($return);die;
                                Session::set("accessToken",$return->data->accessToken);

                            }

                            Session::set("login_id",$user["id"]);
                            Session::set("employee_id",$user["employee_id"]);
                            Session::set("type",$user["type"]);
                            //getUserId、getUserName、getDeptId、getDeptName
                            Session::set("UserId",$user["employee_id"]);
                            $employee=db("employee")->alias("e")->join("department_employee de","e.id=de.employee_id")->join("department d","d.id=de.department_id")->where("de.index=1 and e.id={$user['employee_id']}")->field("em_name,d.id,d.de_name")->find();
                            Session::set("UserName",$employee["em_name"]);
                            Session::set("DeptId",$employee["id"]);
                            Session::set("DeptName",$employee["de_name"]);
                            //测试
                            
    						return $this->redirect("Index/index");
    					}else{
    						//帐号冻结
    						return $this->redirect("Login/signin",['msg'=>3,'lname'=>$data["login_name"]]);
    					}
    				}else{
    					//帐号或密码错误
    					return $this->redirect("Login/signin",['msg'=>2,'lname'=>$data["login_name"]]);
    				}
    			}else{
    				//帐号或密码错误
    				return $this->redirect("Login/signin",['msg'=>2,'lname'=>$data["login_name"]]);
    			}
    		}
    		else{
    			//验证码错误
    			return $this->redirect("Login/signin",['msg'=>1,'lname'=>$data["login_name"]]);
    		}

    	}else{
    		return $this->redirect("Login/signin");
    	}

    }
    public function logout(){
        Session::clear();
        return $this->redirect("Index/index");
    }
    //登录验证吗
  	public function loginVerifyCode(){
  		$this->verifyCode(1,4,80,34);
  		
  	}

  	 //验证码
  //$num验证码长度
  //$width验证码宽度
  //$height验证码高度
  //$type验证码形态  1纯数字  2纯字母大小写   3字母数字
   function verifyCode($type=1,$num=4,$width=80,$height=25){
	
		$code=array();
		$start=0;$end=2;
		switch ($type) {
			case 1:
				# code...
				$start=0;$end=0;
				break;
			case 2:
				# code...
				$start=1;$end=2;
				break;
			case 3:
				# code...
				$start=0;$end=2;
				break;
			
		}
		for($i=0;$i<$num;$i++)//生成验证码
		{

		 	switch(rand($start,$end))
		 	{
		 		case 0:$code[$i]=chr(rand(48,57));break;//数字
		 		case 1:$code[$i]=chr(rand(65,90));break;//大写字母
		 		case 2:$code[$i]=chr(rand(97,122));break;//小写字母
		 	}
			
		}
		
		
		$codetext=md5(strtolower(implode('',$code)));
		Session::set("verify",$codetext);
		$image=imagecreate($width,$height);
		imagecolorallocate($image,255,255,255);
		for($i=0;$i<$num;$i++)//打印字符到图像
		{
			$char_color=imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
			imagechar($image,60,($width/$num)*$i,rand(0,5),$code[$i],$char_color);
		}
		ob_get_clean();
		header("Content-type: image/PNG");
		imagepng($image);//输出图像到浏览器
		imagedestroy($image);//释放资源
		
	}
}
